<template>
  <canvas ref="canvas" class="particle-canvas"></canvas>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref<any>(null)
let animationFrameId:any = null

onMounted(() => {
  const ctx = canvas.value.getContext('2d')
  let particles:any = []

  // 设置canvas尺寸为窗口大小
  const resizeCanvas = () => {
    canvas.value.width = window.innerWidth
    canvas.value.height = window.innerHeight
  }
  
  // 创建粒子类
  class Particle {
    x: number
    y: number
    size: number
    speedX: number
    speedY: number
    color: string
    constructor() {
      this.x = Math.random() * canvas.value.width
      this.y = Math.random() * canvas.value.height
      this.size = Math.random() * 2 + 1
      this.speedX = Math.random() * 2 - 1
      this.speedY = Math.random() * 2 - 1
      this.color = `rgba(255, 255, 255, ${Math.random() * 0.5 + 0.2})`
    }

    update() {
      this.x += this.speedX
      this.y += this.speedY

      if (this.x > canvas.value.width) this.x = 0
      if (this.x < 0) this.x = canvas.value.width
      if (this.y > canvas.value.height) this.y = 0
      if (this.y < 0) this.y = canvas.value.height
    }

    draw() {
      ctx.fillStyle = this.color
      ctx.beginPath()
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
      ctx.fill()
    }
  }

  // 初始化粒子
  const init = () => {
    particles = [];
    const numberOfParticles = Math.floor((canvas.value.width * canvas.value.height) / 15000)
    for (let i = 0; i < numberOfParticles; i++) {
      particles.push(new Particle() as unknown as never);
    }
  }

  // 连接临近的粒子
  const connect = () => {
    for (let i = 0; i < particles.length; i++) {
      for (let j = i + 1; j < particles.length; j++) {
        const dx = particles[i].x - particles[j].x
        const dy = particles[i].y - particles[j].y
        const distance = Math.sqrt(dx * dx + dy * dy)

        if (distance < 100) {
          ctx.strokeStyle = `rgba(255, 255, 255, ${0.2 - distance/500})`
          ctx.lineWidth = 1
          ctx.beginPath()
          ctx.moveTo(particles[i].x, particles[i].y)
          ctx.lineTo(particles[j].x, particles[j].y)
          ctx.stroke()
        }
      }
    }
  }

  // 动画循环
  const animate = () => {
    ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
    
    particles.forEach((particle:any) => {
      particle.update()
      particle.draw()
    })
    
    connect()
    animationFrameId = requestAnimationFrame(animate) as never
  }

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    resizeCanvas()
    init()
  })

  resizeCanvas()
  init()
  animate()
})

onUnmounted(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
})
</script>

<style scoped>
.particle-canvas {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
  background: linear-gradient(45deg, #1a1a1a, #2c2c2c);
}
</style> 